const mysql = require('mysql2/promise');

async function main() {
    const args = process.argv.slice(2);
    const getArg = (name, def) => {
        const i = args.indexOf(name);
        return i >= 0 && args[i + 1] ? args[i + 1] : def;
    };

    const src = {
        host: getArg('--src-host', process.env.SRC_DB_HOST || ''),
        port: parseInt(getArg('--src-port', process.env.SRC_DB_PORT || '3306'), 10),
        user: getArg('--src-user', process.env.SRC_DB_USER || ''),
        password: getArg('--src-pass', process.env.SRC_DB_PASS || ''),
        database: getArg('--src-db', process.env.SRC_DB_NAME || ''),
    };

    const dst = {
        host: getArg('--dst-host', process.env.DB_HOST || '43.143.253.188'),
        port: parseInt(getArg('--dst-port', process.env.DB_PORT || '3306'), 10),
        user: getArg('--dst-user', process.env.DB_USER || 'nextjs'),
        password: getArg('--dst-pass', process.env.DB_PASS || 'yEAiRE2jcxTyRBy5'),
        database: getArg('--dst-db', process.env.DB_NAME || 'nextjs'),
    };

    if (!src.host || !src.user || !src.database) {
        console.error('请提供备用库连接参数，例如: --src-host 1.2.3.4 --src-user root --src-pass xxx --src-db backup');
        process.exit(1);
    }

    let srcConn, dstConn;
    try {
        srcConn = await mysql.createConnection(src);
        dstConn = await mysql.createConnection(dst);

        await dstConn.beginTransaction();
        const [rows] = await srcConn.execute(
            'SELECT level, experience, created_at, updated_at, COALESCE(standard_exp_per_fight, NULL) AS standard_exp_per_fight FROM level_experience ORDER BY level'
        );

        await dstConn.execute('DELETE FROM level_experience');

        const insertSql = 'REPLACE INTO level_experience (level, experience, standard_exp_per_fight, created_at, updated_at) VALUES (?, ?, ?, ?, ?)';
        for (const r of rows) {
            const created = r.created_at ? new Date(r.created_at) : new Date();
            const updated = r.updated_at ? new Date(r.updated_at) : new Date();
            await dstConn.execute(insertSql, [r.level, r.experience, r.standard_exp_per_fight || null, created, updated]);
        }

        await dstConn.commit();
        console.log(`已恢复 level_experience 共 ${rows.length} 行至目标库`);
    } catch (e) {
        if (dstConn) await dstConn.rollback().catch(() => { });
        console.error('恢复失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (srcConn) await srcConn.end();
        if (dstConn) await dstConn.end();
    }
}

main().catch((e) => {
    console.error(e);
    process.exit(1);
});
